package com.to8to.kitt;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;


public class TNettyTransport extends TTransport {
	
	private Channel channel;
	
    private ByteBuf buff;

    public TNettyTransport(Channel channel, ByteBuf  buff) {
    	this.channel = channel;
    	this.buff = buff;
    }

    @Override
    public boolean isOpen() {
    	if(channel == null)
    		return true;
    	return channel.isOpen();
    }

    @Override
    public void open() throws TTransportException {
    	// the channel must be opened using Netty
    }

    @Override
    public void close() {
    	// Channel is managed via the Netty API
    }

    @Override
    public int read(byte[] buffer, int offset, int length) throws TTransportException {
        
    	int readableBytes = buff.readableBytes();
        
        int bytesToRead = Math.min(length, readableBytes);

        buff.readBytes(buffer, offset, bytesToRead);
        
        return bytesToRead;
    }

    @Override
    public void write(byte[] buffer, int offset, int length) throws TTransportException {
    	buff.writeBytes(buffer, offset, length);
    }

    public ByteBuf getBuf() {
        return buff;
    }

}
